package com.weifly.weistock.record.asset.impl;

import com.weifly.weistock.record.asset.AssetConfigService;
import com.weifly.weistock.record.asset.domain.AssetDayDto;
import com.weifly.weistock.record.asset.domain.AssetYearDto;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户资产配置服务实现
 *
 * @author weifly
 * @since 2019/9/17
 */
public class AssetConfigServiceImpl implements AssetConfigService {

    private Logger log = LoggerFactory.getLogger(AssetConfigServiceImpl.class);

    private static final String ELE_ROOT = "root";
    private static final String ELE_RECORD = "record";
    private static final String ATTR_YEAR = "year";
    private static final String ATTR_DAY = "day";
    private static final String ATTR_ASSET = "asset";

    private String configPath; // 配置文件路径

    public void setConfigPath(String configPath) {
        this.configPath = configPath;
    }

    @Override
    public List<AssetYearDto> loadYearList() {
        List<AssetYearDto> yearList = new ArrayList<>();

        File configFolder = new File(this.configPath);
        if(!configFolder.exists()){
            log.info("资产记录目录不存在：" + configFolder.getAbsolutePath());
            return yearList;
        }

        for(File xmlFile : configFolder.listFiles()){
            if(xmlFile.getName().endsWith(".xml")){
                log.info("加载资产记录：" + xmlFile.getAbsolutePath());
                AssetYearDto yearDto = this.loadYearXml(xmlFile);
                yearList.add(yearDto);
            }
        }
        return yearList;
    }

    private AssetYearDto loadYearXml(File xmlFile){
        AssetYearDto yearDto = new AssetYearDto();
        try{
            SAXReader reader = new SAXReader();
            Document document = reader.read(xmlFile);
            Element rootEle = document.getRootElement();

            String year = rootEle.attributeValue(ATTR_YEAR);
            yearDto.setYear(year);

            List<Element> recordEleList = rootEle.elements(ELE_RECORD);
            if(recordEleList!=null){
                for(Element recordEle : recordEleList){
                    AssetDayDto dayDto = new AssetDayDto();
                    String day = recordEle.attributeValue(ATTR_DAY);
                    dayDto.setDay(day);
                    String assetStr = recordEle.attributeValue(ATTR_ASSET);
                    double asset = Double.parseDouble(assetStr);
                    dayDto.setAsset(asset);
                    yearDto.getDayList().add(dayDto);
                }
            }
            return yearDto;
        }catch(DocumentException e){
            log.error("", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveYear(AssetYearDto yearDto) {
        File configFolder = new File(this.configPath);
        if(!configFolder.exists()){
            configFolder.mkdirs();
        }

        DocumentFactory factory = DocumentFactory.getInstance();

        Document document = factory.createDocument();
        document.setXMLEncoding("UTF8");

        Element rootEle = factory.createElement(ELE_ROOT);
        rootEle.addAttribute(ATTR_YEAR, yearDto.getYear());
        document.setRootElement(rootEle);

        for(AssetDayDto dayDto : yearDto.getDayList()){
            Element recordEle = factory.createElement(ELE_RECORD);
            recordEle.addAttribute(ATTR_DAY, dayDto.getDay());
            recordEle.addAttribute(ATTR_ASSET, String.valueOf(dayDto.getAsset()));
            rootEle.add(recordEle);
        }

        FileOutputStream output = null;
        try{
            File xmlFile = new File(configFolder, "asset_" + yearDto.getYear() + ".xml");
            log.info("保存资产记录, file={}", xmlFile.getAbsolutePath());
            output = new FileOutputStream(xmlFile);
            OutputFormat format = new OutputFormat("  ", true, "UTF8");
            XMLWriter writer = new XMLWriter(output, format);
            writer.write(document);
            writer.close();
        }catch(IOException e){
            throw new RuntimeException(e);
        }finally {
            IOUtils.closeQuietly(output);
        }
    }
}
